<template>
  <div class="w-screen h-screen p-3 box-border">
    <div class="flex w-full h-full">
      <div class="flex-[2] relative">
        <div
          class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold"
        >
          <div class="flex items-center justify-center">
            <el-form :inline="true">
              <el-form-item label="模式">
                <el-select
                  v-model="modeValue"
                  placeholder="请选择"
                  @change="handleModeChange"
                  style="width: 100px"
                >
                  <el-option
                    v-for="item in modeList"
                    :key="item.idx"
                    :label="item.value"
                    :value="item.key"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="分辨率">
                <el-select
                  v-model="resolutionValue"
                  placeholder="请选择"
                  @change="handleResolutionChange"
                  style="width: 120px"
                >
                  <el-option
                    v-for="(item, index) in resolutionList"
                    :key="index"
                    :label="item"
                    :value="item"
                  />
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <div
          class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded flex items-center justify-center"
        >
          <div
            class="absolute top-3 left-3 text-center text-sm text-[#333] font-bold"
          >
            当前动作：{{ actionValue || "-" }}
          </div>

          <div
            class="absolute top-3 right-3 text-center text-sm text-[#333] font-bold flex items-center justify-center"
          >
            web服务状态：{{ isConnected ? "已连接" : "未连接" }}
            <el-button type="primary" link @click="handleShowPreviewWindow"
              >显示WEB服务窗口</el-button
            >
          </div>
          <img
            v-if="isConnected"
            :src="mainCamera"
            width="640"
            height="480"
            class="bg-gray-500/10 rounded"
            alt="主摄像头"
          />
          <el-result v-else title="提示" sub-title="视频已关闭，请重新打开">
            <template #icon>
              <img src="/assets/image/bg-stop.png" />
            </template>
            <template #extra>
              <el-button type="primary" @click="handleStartVideo"
                >重新打开</el-button
              >
            </template>
          </el-result>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div
            class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-start"
          >
            <div
              v-if="!isConnected"
              class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10"
            >
              <div class="text-center text-sm text-[#fff] font-bold">
                正在获取视频流，请稍等...，请勿关闭页面，否则视频流将无法正常显示
              </div>
              <div class="text-center text-sm text-[#fff] font-bold">
                如果长时间无法获取视频流，请检查高拍仪是否正常连接，或者重启高拍仪，关闭页面后重新打开
              </div>
            </div>
            <div
              class="flex flex-col items-center justify-center cursor-pointer w-20"
              @click="handleStartVideo"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon_start.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">重开视频</div>
            </div>
            <div
              class="flex flex-col items-center justify-center cursor-pointer w-20"
              @click="handleStopVideo"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon_stop.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">关闭视频</div>
            </div>
            <div
              class="flex flex-col items-center justify-center cursor-pointer w-20"
              @click="handleCropVideo"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon_cb.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">纠偏裁边</div>
            </div>
            <div
              class="flex flex-col items-center justify-center w-20 cursor-pointer"
              @click="handleZoomIn"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon_enlarge.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">点击放大</div>
            </div>
            <div
              class="flex flex-col items-center justify-center w-20 cursor-pointer"
              @click="handleZoomOut"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon_narrow.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">点击缩小</div>
            </div>

            <div
              class="flex flex-col items-center justify-center cursor-pointer w-20"
              @click="handleChangeVideo"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img
                  class="w-6 h-5"
                  src="/assets/image/icon_toggle_camera.png"
                />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">切换摄像头</div>
            </div>
            <el-tooltip placement="top" effect="light">
              <template #content>
                <div class="flex items-center justify-center my-2">
                  <div
                    class="flex flex-col items-center justify-center w-20 cursor-pointer"
                    @click="handleRotateLeft"
                  >
                    <div
                      class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
                    >
                      <img
                        class="w-6 h-6"
                        src="/assets/image/icon-left-hander.png"
                      />
                    </div>
                    <div class="text-xs text-[#333] mt-2 font-bold">
                      点击左旋
                    </div>
                  </div>
                  <div
                    class="flex flex-col items-center justify-center w-20 cursor-pointer"
                    @click="handleRotateRight"
                  >
                    <div
                      class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
                    >
                      <img
                        class="w-6 h-6"
                        src="/assets/image/icon-right-hander.png"
                      />
                    </div>
                    <div class="text-xs text-[#333] mt-2 font-bold">
                      点击右旋
                    </div>
                  </div>
                </div>
              </template>
              <div
                class="flex flex-col items-center justify-center cursor-pointer w-20"
              >
                <div
                  class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
                >
                  <img class="w-5 h-5" src="/assets/image/icon_more.png" />
                </div>
                <div class="text-xs text-[#333] mt-2 font-bold">更多...</div>
              </div>
            </el-tooltip>
          </div>
          <div
            class="w-40 bg-blue-200/15 p-4 box-border ml-4 rounded flex items-center justify-center"
          >
            <div
              class="flex flex-col items-center justify-center cursor-pointer w-20"
              @click="handleTakePicture"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon-camer.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">开始读取</div>
            </div>
          </div>
        </div>
      </div>
      <div class="flex-[1] ml-3 relative">
        <div>
          <div
            class="flex bg-blue-200/15 px-4 h-16 box-border rounded items-center justify-start text-base text-[#333] font-bold"
          >
            图片展示区
          </div>
        </div>
        <div
          class="absolute top-[76px] left-0 bottom-[108px] w-full bg-blue-200/15 rounded"
        >
          <div class="flex flex-wrap p-4 rounded">
            <el-image
              alt="点击预览"
              v-for="(item, index) in base64PicturesList"
              :key="index"
              :src="item"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :preview-src-list="base64PicturesList"
              :initial-index="4"
              fit="cover"
              class="cursor-pointer rounded"
            />
          </div>
          <div
            v-if="currentTitle"
            class="text-center text-sm text-[#333] font-bold mt-4"
          >
            当前操作： {{ currentTitle }}
          </div>
        </div>
        <div class="flex justify-between absolute bottom-0 left-0 right-0">
          <div
            class="flex flex-1 bg-blue-200/15 p-4 box-border rounded items-center justify-end"
          >
            <div
              v-if="!isConnected"
              class="absolute top-0 left-0 w-full h-full bg-black/20 flex flex-col items-center justify-center z-10"
            >
              <div class="text-center text-sm text-[#fff] font-bold">
                请勿关闭页面，否则视频流将无法正常显示
              </div>
            </div>
            <div
              class="flex flex-col items-center justify-center w-20 cursor-pointer"
              @click="handleShowInfo"
            >
              <div
                class="w-10 h-10 bg-[#7fcef5] rounded-sm flex items-center justify-center hover:bg-blue-400"
              >
                <img class="w-6 h-6" src="/assets/image/icon-info.png" />
              </div>
              <div class="text-xs text-[#333] mt-2 font-bold">读取信息</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
import { Warning } from "@element-plus/icons-vue";
const isConnected = ref(false); // 连接状态
const resolutionList = ref([]); // 分辨率列表
const resolutionValue = ref(""); // 分辨率值
const modeList = ref([]); // 模式列表
const modeValue = ref("1"); // 模式值
const base64PicturesList = ref([]); // 图片列表
const angleValue = ref(""); // 角度值
const actionValue = ref(""); // 操作值
const currentTitle = ref(""); // 当前标题
const mainCamera = ref(""); // 主摄像头
const cropOpen = ref(0); // 纠偏裁边
let currentZoomLevel = ref(0); // 当前放大倍数
let loading = null; // 加载状态
let url = "http://127.0.0.1:38088"; // 高拍仪地址

const isConnectedToMachine = async () => {
  try {
    const response = await useFetch(url + "/device=isconnect", {
      method: "POST",
    });
    if (response.data.value.code == 0) {
      return true;
    } else {
      return false;
    }
  } catch (error) {
    console.error("Error checking connection:", error);
    return false;
  }
};

// 初始化分辨率
const fetchResolution = async (camidx, mode, key, value) => {
  const random = Math.random(); //创建随机数
  const response = await useFetch(url + "/device=getresolution?" + random, {
    method: "POST",
    body: JSON.stringify({ camidx, mode }),
  });
  if (
    response.data.value.code == 0 &&
    response.data.value.data.split("|").length > 1
  ) {
    const data = { key, value };
    modeList.value.push(data);
    if (value == "MJPG") loadMainCameraResolution();
  } else ElMessage.error("分辨率获取失败");
};

const initializeResolutionAndMode = () => {
  // 初始化分辨率
  fetchResolution("0", "1", "1", "MJPG");

  // 初始化模式
  fetchResolution("0", "0", "0", "YUY2");
};

const initializeCameraSettings = async () => {
  const falg = await isConnectedToMachine();
  const random = Math.random(); //创建随机数
  console.log("falg", falg);
  if (falg) {
    console.log("初始化分辨率");
    isConnected.value = true;
    mainCamera.value = "";
    mainCamera.value = url + "/video=stream&camidx=0?" + random;
    initializeResolutionAndMode();
  } else {
    isConnected.value = false;
    ElMessageBox.confirm(
      "请先连接设备, 或者检查插件设备是否正常连接，关闭页面后重新打开",
      "提示",
      {
        type: "warning",
        icon: markRaw(Warning),
        showCancelButton: false,
        confirmButtonText: "知道了",
      }
    );
  }
};

initializeCameraSettings();

// 加载主摄像头分辨率
const loadMainCameraResolution = async () => {
  const view1ResolutionPowerData = {
    camidx: 0,
    mode: Number(modeValue.value),
  };
  try {
    const random = Math.random(); //创建随机数
    const response = await useFetch(url + "/device=getresolution?" + random, {
      method: "POST",
      body: JSON.stringify(view1ResolutionPowerData),
    });
    console.log("Response:", response); // 打印响应
    if (response.data.value.code == 0) {
      const list = response.data.value.data.split("|");
      resolutionValue.value = list[0];
      resolutionList.value = [...list, ...resolutionList.value];
      handleActionChange("视频打开成功");
    } else ElMessage.error("视频打开失败");
  } catch (error) {
    console.error("Error loading main camera resolution:", error);
  }
};

// 分辨率改变
// 模式改变
const handleModeChange = (value) => {
  modeValue.value = value;
  loadMainCameraResolution();
};

// 分辨率改变
const handleResolutionChange = (value) => {
  resolutionValue.value = value;
  setResolution();
};

// 设置分辨率
const setResolution = async () => {
  const resolutionData = {
    camidx: 0, // 主头
    mode: Number(modeValue.value),
    width: parseInt(resolutionValue.value.split("*")[0]),
    height: parseInt(resolutionValue.value.split("*")[1]),
  };
  try {
    const response = await useFetch(url + "/device=setresolution", {
      method: "POST",
      body: JSON.stringify(resolutionData),
    });
    console.log("Resolution set successfully:", response);
    if (response.data.value.code == 0) {
      ElMessage.success("设置分辨率成功");
      handleActionChange(`设置分辨率`);
    } else {
      ElMessage.error("设置分辨率失败");
      handleActionChange(`设置分辨率失败`);
    }
  } catch (error) {
    console.error("Error setting resolution:", error);
  }
};

// 打开视频
const handleStartVideo = async () => {
  const flag = await isConnectedToMachine();
  console.log("flag", flag);
  const random = Math.random(); //创建随机数
  if (flag) {
    mainCamera.value = "";
    mainCamera.value =
      url +
      `/video=stream&camidx=0&resolution=${resolutionValue.value}&mode=${modeValue.value}?${random}`;
    isConnected.value = true;
    handleActionChange("打开视频");
  } else {
    ElMessage.error("请先连接设备, 或者检查插件设备是否正常连接");
  }
};

// 关闭视频
const handleStopVideo = () => {
  const command = { camidx: "0" };
  useFetch(url + "/video=close", {
    method: "POST",
    body: JSON.stringify(command),
  })
    .then(() => {
      mainCamera.value = "";
      isConnected.value = false;
      console.log("关闭主摄像头成功");
    })
    .catch((error) => {
      console.error("关闭主摄像头失败:", error);
    });
  handleActionChange("关闭视频");
};

// 旋转
const handleAngleChange = async (value) => {
  angleValue.value = value;
  let data = {
    camidx: "0",
    rotate: String(angleValue.value),
    time: Date.now(),
  };
  try {
    await useFetch(url + "/video=rotate", {
      method: "POST",
      body: JSON.stringify(data),
    });
    console.log("旋转" + String(angleValue.value) + "度成功");
    handleActionChange("旋转" + String(angleValue.value) + "度");
  } catch (error) {
    console.error("旋转失败:", error);
    handleActionChange("旋转失败");
  }
};

// 左旋
const handleRotateLeft = () => {
  handleAngleChange(90);
};

// 右旋
const handleRotateRight = () => {
  handleAngleChange(270);
};

// 放大
const handleZoom = (corpValue) => {
  const command = { action: 0, corp: corpValue };
  useFetch(url + "/stream=zoominout", {
    method: "POST",
    body: JSON.stringify(command),
  })
    .then(() => {
      console.log(`设置主摄像头缩放成功，corp值: ${corpValue}`);
    })
    .catch((error) => {
      console.error(`设置主摄像头缩放失败，corp值: ${corpValue}`, error);
    });
};

// 放大
const handleZoomIn = () => {
  if (currentZoomLevel.value < 9) {
    currentZoomLevel.value += 1;
    handleActionChange(`放大主摄像头，当前放大倍数：${currentZoomLevel.value}`);
    handleZoom(currentZoomLevel.value);
  } else {
    handleActionChange("已达到最大放大倍数");
  }
};

// 缩小
const handleZoomOut = () => {
  if (currentZoomLevel.value > 0) {
    currentZoomLevel.value -= 1;
    handleActionChange(`缩小主摄像头，当前缩小倍数：${currentZoomLevel.value}`);
    handleZoom(currentZoomLevel.value);
  } else {
    handleActionChange("已达到最小缩小倍数");
  }
};

// 纠偏裁边
const handleCropVideo = async () => {
  const random = Math.random(); //创建随机数
  cropOpen.value = cropOpen.value == 0 ? 1 : 0;
  const response = await useFetch(url + "/dvideo=cameradeskew?" + random, {
    method: "POST",
    body: JSON.stringify({ camidx: "0", open: cropOpen.value }),
  });
  console.log("response", response);
  if (response.data.value.code == 0) {
    ElMessage.success(`纠偏裁边${cropOpen.value == 0 ? "关闭" : "开启"}成功`);
    handleActionChange(`纠偏裁边${cropOpen.value == 0 ? "关闭" : "开启"}成功`);
  } else {
    ElMessage.error("纠偏裁边失败");
  }
};

// 切换摄像头
const handleChangeVideo = async () => {
  const falg = await isConnectedToMachine();
  if (falg) {
    const camidx = mainCamera.value.includes("camidx=0") ? 1 : 0;
    mainCamera.value =
      url +
      `/video=stream&camidx=${camidx}&resolution=${resolutionValue.value}&mode=${modeValue.value}`;
    handleActionChange(`切换摄像头，当前摄像头：${camidx === 0 ? "主" : "副"}`);
    isConnected.value = true;
    initializeResolutionAndMode();
  } else {
    ElMessage.error("请先连接设备, 或者检查插件设备是否正常连接");
    handleActionChange("切换摄像头失败");
  }
};

// 拍照
const handleTakePicture = async () => {
  loading = ElLoading.service({
    lock: true,
    text: "拍照中...",
    background: "rgba(0, 0, 0, 0.7)",
  });
  // 0:主摄像头；1:副摄像头
  const camidx = mainCamera.value.includes("camidx=0") ? "0" : "1";
  //
  let command = {
    filepath: "base64",
    rotate: "0",
    cutpage: "0",
    camidx: camidx,
    ColorMode: "0",
    quality: "1", //0:默认质量；1:高质量；2:较高质量；3:中质量；4:较低质量；5:低质量
    deskew: cropOpen.value,
    deskewval: 10,
    bAutoAdjust: "0",
  };

  const response = await useFetch(url + "/video=grabimage", {
    method: "POST",
    body: JSON.stringify(command),
  });

  if (response.data.value) {
    ElMessage.success("拍照成功");
    base64PicturesList.value = [
      "data:image/jpg;base64," + response.data.value.photoBase64,
    ];
    handleActionChange(`拍照成功，当前摄像头：${camidx === "0" ? "主" : "副"}`);
    loading.close();
  } else {
    console.error("拍照失败:", response);
    ElMessage.error("拍照失败");
    loading.close();
    handleActionChange("拍照失败");
  }
};

// 显示预览窗口
const handleShowPreviewWindow = async () => {
  const response = await useFetch(url + "/show=previewwindow", {
    method: "POST",
    body: JSON.stringify({ index: 0 }),
  });
  console.log("response", response);
  if (response.data.value.code == 0) {
    ElMessage.success("显示预览窗口成功");
    handleActionChange("显示预览窗口成功");
  } else {
    ElMessage.error("显示预览窗口失败");
    handleActionChange("显示预览窗口失败");
  }
};

const handleShowInfo = () => {
  handleActionChange("正在识别信息");
  console.log("handleShowInfo");
  // 判断是否存在
  if (base64PicturesList.value.length > 0) {
    // 获取iframe的父窗口
    const parentWindow = window.parent;

    // 构造要发送的数据
    var data = {
      action: "LTScannerBase64Img",
      message: base64PicturesList.value,
    };
    // 发送消息
    parentWindow.postMessage(JSON.stringify(data), "*");
    handleActionChange("识别信息成功，等待验证");
  } else {
    console.log("base64PicturesList.value", base64PicturesList.value);
    ElMessage.error("请先拍照");
  }
};

const handleActionChange = (value) => {
  actionValue.value = value;
};

const getFromURL = () => {
  const urlParams = new URLSearchParams(window.location.search);
  const title = urlParams.get("title");
  currentTitle.value = title;
};

onMounted(() => {
  // 获取参数
  getFromURL();
});

onUnmounted(() => {});
</script>
<style lang="scss" scoped>
:deep(.el-form-item) {
  margin-bottom: 0;
}
</style>
